package com.hxgis.oc.util;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;

@Slf4j
public class PNGConvert {
    private final int width;
    private final int height;
    private final float[] values1;
    private final float[] values2;

    @Setter
    @Getter
    private float clampMin = 0.0f;

    @Setter
    @Getter
    private float clampMax = 100.0f;

    @Setter
    @Getter
    private float fixValue = 0.0f;

    public PNGConvert(int width1, int height1, float[] floats, float[] floats1) {
        width = width1;
        height = height1;
        values1 = floats;
        values2 = floats1;
    }

    float clamp(float v, float min, float max){
        return v > max ? max : Math.max(v, min);
    }

    byte decode(float value)
    {
        float value1 = clamp(value + fixValue,clampMin,clampMax);
        float b = (value1 - clampMin) / (clampMax - clampMin) * 255.0f;
        return (byte)b;
    }

    public void write(File outputFile){
        boolean grayChannel = values2 == null;

        int imageType = grayChannel ? BufferedImage.TYPE_BYTE_GRAY : BufferedImage.TYPE_3BYTE_BGR;

        BufferedImage bufferedImage = new BufferedImage(width, height, imageType);
        byte[] buffer = ((DataBufferByte)bufferedImage.getRaster().getDataBuffer()).getData();

        float dMin = 10000.0f;
        float dMax = -1000.0f;
        for(int row = 0;row<height;row++){
            for(int col = 0;col<width;col++){
                int i = (height - row - 1) * width + col;
                float v = values1[i];
                if(v > dMax) dMax = v;if(v < dMin) dMin = v;
                byte r = decode(v);
                int i2 = row * width + col;
                if(grayChannel) {
                    buffer[i2] = r;
                }
                else {
                    float v2 = values2[i];
                    byte g = decode(v2);
                    if(v2 > dMax) dMax = v2;if(v2 < dMin) dMin = v2;
                    buffer[i2 * 3] = 0;
                    buffer[i2 * 3 + 1] = g;
                    buffer[i2 * 3 + 2] = r;
                }
            }
        }
        log.debug("Min:{},Max:{}",dMin + fixValue,dMax + fixValue);

        try {
            ImageIO.write(bufferedImage, "png", outputFile);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
